#!/usr/bin/perl
#
# Mark counter user records as bad, using data from temp_frozen
# Note - run this IMMEDIATELY after a freezefolks run.
#
use Counter;
use POSIX qw(strftime);
use DBI;
use Getopt::Long;

use vars qw($freeze $test $users $dbh $sth);

GetOptions("freeze" => \$dofreeze,
           "good" => \$domarkgood,
	   "test" => \$test);


if ($dofreeze) {
    warn "Freezing bad users that are in temp_freeze\n";
} elsif ($domarkgood) {
    warn "Marking as OK all currently BAD that are NOT in temp_freeze\n";
} else {
    warn "Marking as bad all users in temp_freeze\n";
}
if ($test) {
    warn "TEST mode - not modifying db\n";
    $Counter::User::TESTMODE = 1;
}




$users = Counter::open(O_RDWR);


$dbh = $FileTable::dbhandle;

if ($dofreeze) {

    $sth = $dbh->prepare("SELECT temp_freeze.f_key, why from
     temp_freeze, users where temp_freeze.f_key = users.f_key
                and users.state = 'bad'")
    || die "prepare Select failed\n";
} elsif ($domarkgood) {
    $sth = $dbh->prepare("SELECT users.f_key, 'notbad' from
      users LEFT JOIN temp_freeze ON users.f_key = temp_freeze.f_key
      WHERE temp_freeze.f_key IS NULL AND users.state = 'bad'")
    || die "prepare Select failed\n";
} else {
    $sth = $dbh->prepare("SELECT temp_freeze.f_key, why from
     temp_freeze, users where temp_freeze.f_key = users.f_key
                and users.state = 'ok'")
    || die "prepare Select failed\n";
}

$sth->execute() || die "Executing Select failed\n";

$date = strftime "%Y-%m-%d %H:%M:%S", gmtime();

while (($f_key, $why) = $sth->fetchrow_array) {
    ++ $rows;
    $user = $users->get($f_key);
    if ($dofreeze) {
	if ($user->{state} eq "bad") {
	    warn "Freezing $f_key\n";
	    $user->freeze() if !$test;
	} elsif ($user->{state} ne "frozen") {
	    warn "Skipping $f_key - not bad yet, state $$user{state}\n";
	}
    } elsif ($domarkgood) {
	if ($user->{state} eq "bad") {
	    warn "Unmarking $f_key\n";
	    $user->{comment} = "$date: no longer in freeze-target list";
	    $user->{state} = "ok";
	    $user->store() if !$test;
	} else {
	    warn "Skipping $f_key - state $$user{state}\n";
	}
    } else {
	if ($user->{state} eq "ok") {
	    warn "Badding $f_key - reason $why\n";
	    $user->{state} = "bad";
	    $user->{comment} = "$date: to be frozen -reason $why";
	    $user->store() if !$test;
	} elsif ($user->{state} ne "bad" && $user->{state} ne "frozen") {
	    warn "Skipping $f_key - state is $$user{state}, reason $why\n";
	}
    }
}
warn "Found $rows records to update\n";
